<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $table = 'article_cate';

    public function tree()
    {
    	$categorys = $this->all();
		return $this->getTree($categorys, 'cate_name', 'cate_id', 'parent_id');
    }

    /**
	 * 获取分类树
	 * TODO 改为递归无限分类
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	public function getTree($data, $filedName, $fieldId, $fieldPid = 'pid', $rootPid = 0)
	{
		$rstArr = array();
		foreach ($data as $k => $v) {
			if ($v->$fieldPid == $rootPid) {
				$data[$k]['_'.$filedName] = $data[$k]['cate_name'];
				$rstArr[] = $data[$k];
				foreach ($data as $m => $n) {
					if ($n->$fieldPid == $v->$fieldId) {
						$data[$m]['_'.$filedName] = '|--'.$data[$m][$filedName];
						$rstArr[] = $data[$m];
					}
				}
			}
		}
		return $rstArr;
	}
}
